<?php
/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/12
 * Time: 下午5:16
 */

namespace App\Providers;


use App\Plugins\Plugin;
use Illuminate\Support\ServiceProvider;

class PluginServiceProvider extends ServiceProvider
{
    const CONSOLE_PARAM = '--with-plugin=';
    protected $currentPlugin;
    public function __construct($app)
    {
        parent::__construct($app);

        $plugin = $this->getPlugin();
        if ($plugin) {
            $class = $plugin->namespace . '\\'. $plugin->provider;
            if (class_exists($class)) {
                $this->currentPlugin = new $class($app);
            }
        }
    }

    public function boot()
    {
        if (method_exists($this->currentPlugin, 'boot')) {
            $this->currentPlugin->boot();
        }
    }

    public function register()
    {
        if (method_exists($this->currentPlugin, 'register')) {
            $this->currentPlugin->register();
        }

        if (method_exists($this->currentPlugin, 'map')) {
            $this->currentPlugin->map();
        }
    }

    protected function getPlugin()
    {
        // 命令行模式
        if ($this->app->runningInConsole()) {
            global $argv;
            $pluginName = '';
            foreach ($argv as $value) {
                if (starts_with($value, self::CONSOLE_PARAM)) {
                    $pluginName = substr($value, strlen(self::CONSOLE_PARAM));
                    return (new Plugin)->findByName($pluginName);
                }
            }
        }
        // web模式
        $domain = $_SERVER['HTTP_HOST'] ?? '';
        $alias_domain = explode('.', $domain)[0];
        if (empty($alias_domain))
            return null;

        return (new Plugin)->findByAlias($alias_domain);
    }
}